package com.wxtf.platform.tools;

import java.io.*;
import java.util.zip.*;

/**
 * <li>Title: ZipUtil.java</li>
 * <li>Project: NTCPMS</li>
 * <li>Package: com.crescent.common</li>
 * <li>Description: </li>
 * <li>Copyright: Copyright (c) 2011</li>
 * <li>Company: Crescent Studio </li>
 * <li>Created on Nov 30, 2011 4:44:29 PM</li>
 * 
 * @author chun_chang
 * @version 1.0.0.0
 * 
 */
public class ZipUtil{
	protected static byte buff[] = new byte[1024];
	private static String pdir = "";
	/**
	 * 描述：makeDirectoryToZip
	 * 
	 * @param dir
	 * @throws Exception
	 * @CreateOn Nov 30, 2011 4:52:42 PM
	 * @author chun_chang
	 */
	public static void makeDirectoryToZip(String dir) throws Exception {
		File directory = new File(dir);
		pdir = directory.getParent() + "/";
		String zipName = pdir + directory.getName() + ".zip";
		File zipFile = new File(zipName);
		makeDirectoryToZip(directory, zipFile, 7);
	}
	/**
	 * 创建 ZIP/JAR 文件.
	 * 
	 * @param directory - 要添加的目录
	 * @param zipFile - 保存的 ZIP 文件名
	 * @param level - 压缩级别(0~9)
	 * @throws Exception 
	 */
	public static void makeDirectoryToZip(File directory, File zipFile, int level)
			throws Exception {
		level = checkZipLevel(level);

		ZipOutputStream jos = new ZipOutputStream(new FileOutputStream(zipFile));
		jos.setLevel(level);

		String fileNames[] = directory.list();
		if(fileNames != null) {
			for(int i = 0; i < fileNames.length; i++){
				recurseFiles(jos, new File(directory, fileNames[i]));
			}
		}
		jos.close();
	}
	
	/**
	 * 遍历目录并添加文件.
	 * 
	 * @param jos - JAR 输出流
	 * @param file - 目录文件名
	 * @param pathName - ZIP中的目录名
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private static void recurseFiles(ZipOutputStream jos, File file) throws Exception {
		String pathAll = file.getPath();
		pathAll = pathAll.substring(pdir.length(), pathAll.length());
		if(file.isDirectory()) {
			String fileNames[] = file.list();
			if(fileNames != null) {
				for(int i = 0; i < fileNames.length; i++) {
					recurseFiles(jos, new File(file, fileNames[i]));
				}
			}
		} else {
			ZipEntry jarEntry = new ZipEntry(pathAll);
			FileInputStream fin = new FileInputStream(file);
			BufferedInputStream in = new BufferedInputStream(fin);
			jos.putNextEntry(jarEntry);
			
			int len;
			while((len = in.read(buff)) >= 0){
				jos.write(buff, 0, len);
			}
			in.close();
			jos.closeEntry();
		}
	}
	/**
	 * 检查并设置有效的压缩级别.
	 * 
	 * @param level - 压缩级别
	 * @return 有效的压缩级别或者默认压缩级别
	 */
	public static int checkZipLevel(int level) {
		if(level < 0 || level > 9) {
			level = 7;
		}
		return level;
	}

	public static void main(String[] args){
		try {
			String dir = "/log/";
			ZipUtil.makeDirectoryToZip(dir);
			
			
			
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
